package com.hrm.dept.handler;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.hrm.commons.beans.Dept;
import com.hrm.dept.service.IDeptService;
import com.hrm.utils.PageModel;


@Controller
@RequestMapping("/dept")
public class DeptHandler {
	
	@Autowired
	private IDeptService deptService;
	
	@RequestMapping("/findDept.do")
	public String findDept(@RequestParam(defaultValue="1")Integer pageIndex, Dept dept, Model model) {
		int count = deptService.findDeptCount(dept);
		PageModel pageModel = new PageModel();
		pageModel.setPageIndex(pageIndex);
		pageModel.setRecordCount(count);
		
		List<Dept> depts = deptService.findDept(dept, pageModel);
		
		model.addAttribute("dept", dept);
		model.addAttribute("depts", depts);
		model.addAttribute("pageModel", pageModel);
		return "/jsp/dept/dept.jsp";
	}
	
	@RequestMapping("/addDept.do")
	public String addDept(Dept dept, Model model) {
		int rows = deptService.addDept(dept);
		
		if(rows > 0) {
			return "redirect:/dept/findDept.do";
		}else {
			model.addAttribute("fail", "添加部门失败！");
			return "/jsp/fail.jsp";
		}
	}
	
	@RequestMapping("/findDeptById.do")
	public String findDeptById(Integer id, Model model) {
		Dept dept = deptService.findDeptById(id);
		model.addAttribute("dept", dept);
		
		return "/jsp/dept/showUpdateDept.jsp";
	}
	@RequestMapping("/modifyDept.do")
	public String modifyDept(Dept dept, Model model) {
		int rows = deptService.modifyDept(dept);
		if(rows > 0) {
			return "redirect:/dept/findDept.do";
		}else {
			model.addAttribute("fail", "修改部门失败！");
			return "/jsp/fail.jsp";
		}
	}
	
	@RequestMapping("/removeDept.do")
	public String removeDept(String ids, Model model) {
		String[] idArray = ids.split(",");
		int i = 0;
		for(String s:idArray) {
			int rows = deptService.removeDept(Integer.parseInt(s));
			if(rows > 0) {
				i++;
			}
		}
		if(i == idArray.length) {
			return "redirect:/dept/findDept.do";
		}else {
			model.addAttribute("fail", "删除部门失败！");
			return "/jsp/fail.jsp";
		}
	}
}
